package lk.config;import org.springframework.security.core.authority.SimpleGrantedAuthority;



import com.fasterxml.jackson.databind.ObjectMapper;
import com.lk.util.ResponseUtil;
import com.lk.constant.SecurityConstant;
import lk.util.PasswordUtil;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

/**
 * author lk
 *
 * @date 2021/10/27 11:10
 * @description 简单的授权
 * @since 1.0
 */
public class AuthFilter extends GenericFilterBean {


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request=(HttpServletRequest) servletRequest;
        String header = request.getHeader(SecurityConstant.TOKEN_HEADER);
        if (header!=null) {
            ArrayList<GrantedAuthority> authorities = new ArrayList<>();
            authorities.add(new SimpleGrantedAuthority("/test1"));
            UsernamePasswordAuthenticationToken authentication = new
                    UsernamePasswordAuthenticationToken("admin", PasswordUtil.encryptionPassword("admin"), authorities);
            SecurityContextHolder.getContext().setAuthentication(authentication);
            filterChain.doFilter(request, servletResponse);
        } else  {
            HttpServletResponse response=(HttpServletResponse) servletResponse;
            ResponseUtil.responseFailed(new ObjectMapper(),response,"没有权限");
        }


    }
}
